const express = require("express");
const router = express.Router();

// 模拟数据
let users = [
  { id: 1, name: "John", age: 30 },
  { id: 2, name: "Jane", age: 25 },
];

// 获取所有用户
router.get("/", (req, res) => {
  res.json(users);
});

// 根据 ID 获取单个用户
router.get("/:id", (req, res) => {
  const id = parseInt(req.params.id);
  const user = users.find((u) => u.id === id);
  if (user) {
    res.json(user);
  } else {
    res.status(404).send("User not found");
  }
});

// 创建新用户
router.post("/", (req, res) => {
  const newUser = req.body;
  console.log(req);
  newUser.id = users.length + 1;
  users.push(newUser);
  res.json(users);
});

// 根据 ID 更新用户信息
router.put("/:id", (req, res) => {
  const id = parseInt(req.params.id);
  const updatedUser = req.body;
  const index = users.findIndex((u) => u.id === id);
  if (index !== -1) {
    users[index] = { ...users[index], ...updatedUser };
    res.json(users[index]);
  } else {
    res.status(404).send("User not found");
  }
});

// 根据 ID 删除用户
router.delete("/:id", (req, res) => {
  const id = parseInt(req.params.id);
  const index = users.findIndex((u) => u.id === id);
  if (index !== -1) {
    const deletedUser = users.splice(index, 1)[0];
    res.json(deletedUser);
  } else {
    res.status(404).send("User not found");
  }
});

module.exports = router;
